﻿using FireBillBook.Core.Models;
using FireBillBook.Core.Services;
using FireBillBook.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FireBillBook.Core.Models.QueryContexts;
using FireBillBook.Core.Entities;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace FireBillBook.Controllers
{
    [Route("api/ThirdParty")]
    [ApiController]
    public class ThirdPartyDataController : ControllerBase
    {
        private ILogger _logger;

        public ThirdPartyDataController(IBillingService billing, ILogger<ThirdPartyDataController> logger)
        {
            _logger = logger;
        }

        [HttpPost("[action]")]
        public async Task<IActionResult> Import([FromForm] UploadPaymentModel model, IFormFile file, [FromServices] IImportService importService)
        {
            try
            {
                if (file == null)
                {
                    return new JsonResult(new BaseReponseModel()
                    {
                        IsSuccess = false,
                        Code = -1,
                        Message = "没有找到上传的文件"
                    });
                }

                await importService.Import(model.Platform, file);

                return new JsonResult(new BaseReponseModel()
                {
                    IsSuccess = true,
                    Code = 0,
                    Message = "success"
                });

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "上传文件失败");
                return new JsonResult(new BaseReponseModel()
                {
                    IsSuccess = false,
                    Code = -1,
                    Message = ex.Message
                });
            }
        }

        [HttpPost("[action]")]
        [ProducesResponseType(typeof(CommonResponseModel<PagingModel<BillingSourceData>>), 200)]
        [ProducesErrorResponseType(typeof(BaseReponseModel))]
        public async Task<BaseReponseModel> List(BillingSourceDataListQueryContext queryContext, [FromServices]IImportService service)
        {
            try
            {
                var result = await service.ListSourceDataAsync(queryContext);

                return new CommonResponseModel<PagingModel<BillingSourceData>>(result)
                {
                    IsSuccess = true
                };
            }
            catch (Exception ex)
            {
                return new BaseReponseModel()
                {
                    IsSuccess = false,
                    Code = -1,
                    Message = ex.Message
                };
            }
        }
    }
}
